//
//  LKJsonRequestManager.m
//  Live
//
//  Created by Pie on 2017/7/26.
//  Copyright © 2017年 LaKa. All rights reserved.
//

#import "LKJsonRequestManager.h"
#import "LKRespondHandler.h"
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "NSString+Helper.h"
#import "NSDictionary+YYAdd.h"
#import "NSString+YYAdd.h"
#import "BNDOfficeDocKit.h"



//#import "NSString+Helper.h"

static const NSTimeInterval LKShopQueryTimeout = 20; // 请求超时
static const NSTimeInterval LKShopResourceQueryTimeout = 30; // 资源请求超时

@interface LKJsonRequestManager ()



@property (strong, nonatomic, readwrite) NSURLSessionDataTask *currentDataTask;
@property (strong, nonatomic, readwrite) NSURL *wholeQureyUrl;

@end

@implementation LKJsonRequestManager

+ (NSURLSessionConfiguration *)sessionConfiguration
{
    NSURLSessionConfiguration *theSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    [theSessionConfiguration setRequestCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [theSessionConfiguration setTimeoutIntervalForRequest:LKShopQueryTimeout];
    [theSessionConfiguration setTimeoutIntervalForResource:LKShopResourceQueryTimeout];
    
    return theSessionConfiguration;
}

+ (instancetype)requestManager:(NSString*)serverUrl
{
    return [[[self class] alloc] initWithBaseURL:[NSURL URLWithString:serverUrl]
                            sessionConfiguration:[self sessionConfiguration]];
}

- (instancetype)initWithBaseURL:(NSURL *)url
           sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
    self = [super initWithBaseURL:url sessionConfiguration:configuration];
    if (self) {
        
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html",@"application/json",@"text/json", @"text/javascript",@"application/x-www-form-urlencoded",nil];
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        [self setCommonHTTPHeaderField];
    }
    return self;
}

#pragma mark - Getter

- (NSURL *)wholeQureyUrl
{
    return self.currentDataTask.currentRequest.URL;
}

#pragma mark - Helper Methods

+ (NSString *)getSubscriberCellularProviderStr
{
    static CTTelephonyNetworkInfo *telephonyInfo;
    if (!telephonyInfo) {
        telephonyInfo = [CTTelephonyNetworkInfo new];
    }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    return telephonyInfo.subscriberCellularProvider.carrierName;
#pragma clang diagnostic pop
}

+ (NSDictionary *)commonHTTPHeaderField
{
//    NSString *systemVersion = [UIDevice currentDevice].systemVersion;
//    NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
//    NSString *shortVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//
//    uint64_t timestamp = [[NSDate date] timeIntervalSince1970];
    
    NSDictionary *commonHeaderField =  @{
//        @"currentCompanyOpenId":@"00ptbnd1908018713159904060714715",
//        @"currentOpenId":@"00ptbnd1962460793159946082614215",
                @"companyOpenId":[BNDPreference sharedInstance].companyOpenId,
                @"openId":[BNDPreference sharedInstance].openId,

        @"currentCompanyOpenId":[BNDPreference sharedInstance].companyOpenId,
        @"currentOpenId":[BNDPreference sharedInstance].openId,
                @"token":[BNDPreference sharedInstance].token,
                                         };
    return commonHeaderField;
}


#pragma mark - Setter


- (void)setCommonHTTPHeaderField
{

    self.commonHTTPHeaders = [LKJsonRequestManager commonHTTPHeaderField];
    [self.commonHTTPHeaders enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
        [self.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    [self.requestSerializer setValue:TTStringNotNil([BNDPreference sharedInstance].token) forHTTPHeaderField:@"Authorization"];
    
    
}

- (NSDictionary*)signatureHTTPQueryParameters:(NSDictionary *)parameters
{
    NSDictionary *signatureDic = [self signWithParameters:parameters];
    return signatureDic;
}

#pragma mark - Public Method

- (void)getJSONWithRelativeUrl:(NSString *)urlStr
                    parameters:(NSDictionary *)parameters
                       success:(LKJsonQuerySuccessBlock)success
                       failure:(LKJsonQueryFailureBlock)failure
{   BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    NSDictionary *allParameters = [self signatureHTTPQueryParameters:parameters];
    
    @weakify(self)
    self.currentDataTask =  [self GET:urlStr parameters:allParameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

- (void)getJSONWithRelativeAllUrl:(NSString *)urlStr
                    parameters:(id)parameters
                       success:(LKJsonQuerySuccessBlock)success
                       failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    @weakify(self)
    self.currentDataTask =  [self GET:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

- (void)postJSONWithRelativeUrl:(NSString *)urlStr
                     parameters:(NSDictionary *)parameters
                        success:(LKJsonQuerySuccessBlock)success
                        failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    NSDictionary *allParameters = [self signatureHTTPQueryParameters:parameters];
    @weakify(self)
    self.currentDataTask = [self POST:urlStr parameters:allParameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
       [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

- (void)postJSONWithRelativeAllUrl:(NSString *)urlStr
                     parameters:(id)parameters
                        success:(LKJsonQuerySuccessBlock)success
                        failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });

    @weakify(self)
    self.currentDataTask = [self POST:urlStr parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
       [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

- (void)postJSONWithUploadPicturesUrl:(NSString *)urlStr
                           parameters:(NSDictionary *)parameters
                            imageData:(NSData *)imageData
                                 type:(NSInteger)type
                              success:(LKJsonQuerySuccessBlock)success
                              failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
       [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
       });
    NSDictionary *allParameters = [self signatureHTTPQueryParameters:parameters];
    @weakify(self)
    
    self.currentDataTask =  [self POST:urlStr parameters:allParameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSDate * today = [NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate:today];
        NSDate *localeDate = [today dateByAddingTimeInterval:interval];
        NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[localeDate timeIntervalSince1970]];//@"1517468580"
        if(type ==1) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%@.mp4",timeSp] mimeType:@"video/mpeg"];
        }else {
            [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%@.jpg",timeSp] mimeType:@"image/jpeg"];
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

- (void)putJSONWithRelativeUrl:(NSString *)urlStr
                     parameters:(NSDictionary *)parameters
                        success:(LKJsonQuerySuccessBlock)success
                        failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    NSDictionary *allParameters = [self signatureHTTPQueryParameters:parameters];
    @weakify(self)
    self.currentDataTask = [self PUT:urlStr parameters:allParameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
       [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
                            

}

#pragma mark - 签名

- (NSDictionary *)signWithParameters:(NSDictionary *)parameters
{
    NSDictionary *noEmptyValueHeaderFeild = [self removeEmptyValueKeys:self.commonHTTPHeaders];
    NSDictionary *noEmptyValueParameters = [self removeEmptyValueKeys:parameters];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict addEntriesFromDictionary:noEmptyValueHeaderFeild];
    [dict addEntriesFromDictionary:noEmptyValueParameters];
    
    NSMutableDictionary *saltDic = [[NSMutableDictionary alloc] init];
       [saltDic addEntriesFromDictionary:dict];
    NSMutableDictionary *sala = [NSMutableDictionary dictionary];
    [sala setValue:@"QQKJ.R0cketAp1Sa1t" forKey:@"salt"];
      [saltDic addEntriesFromDictionary:sala];
    NSArray *keySortArray = [saltDic allKeysSorted];
    
        NSMutableArray *parameterArray = [NSMutableArray array];
        [keySortArray enumerateObjectsUsingBlock:^(NSString * key, NSUInteger idx, BOOL * _Nonnull stop) {
    
            id value = saltDic[key];
            NSString *encodeValue = value;
            NSString *encodeKey = [key lk_formURLEncodedString];
    
//            if ([value isKindOfClass:[NSString class]]) {
//                encodeValue = [value lk_formURLEncodedString];
//            }
    
            [parameterArray addObject:[NSString stringWithFormat:@"%@=%@", encodeKey, encodeValue]];
        }];
    
        NSString *encryptString = [parameterArray componentsJoinedByString:@"&"];
      //  NSString *stringSignTemp = [NSString stringWithFormat:@"%@&salt=QQKJ.R0cketAp1Sa1t", encryptString];
        NSString *stringSign = [encryptString md5String];
        NSString *stringSignTwo = [stringSign md5String];
        [self.requestSerializer setValue:stringSignTwo forHTTPHeaderField:@"Sign"];
    
    return dict;
}


/**
 去掉空字符串的key
 
 @return 返回一个值不是空Vaule的字典
 */
- (NSDictionary *)removeEmptyValueKeys:(NSDictionary *)dict
{
    NSMutableDictionary *noEmptyValueKey = [NSMutableDictionary dictionary];
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        
        if([obj isKindOfClass:[NSString class]] && NSStringIsEmpty(obj)){
            // 如果是字符串并且是空的，就不参与签名
        }else{
            [noEmptyValueKey setObject:obj forKey:key];
        }
    }];
    return noEmptyValueKey;
}

- (void)postJSONWithUploadPhotoUrl:(NSString *)urlStr
                        parameters:(NSDictionary *)parameters
                         imageData:(NSData *)imageData
                              type:(NSInteger)type
                           success:(LKUploadProgressBlock)cmUploadProgres
                           success:(LKJsonQuerySuccessBlock)success
                           failure:(LKJsonQueryFailureBlock)failure
{
    BND_dispatch_main_sync_safe(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
     })
    NSDictionary *allParameters = [self signatureHTTPQueryParameters:parameters];

    @weakify(self)
    
    self.currentDataTask =  [self POST:urlStr parameters:allParameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if(type ==1) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.mp4" mimeType:@"video/mpeg"];
        }else {
            NSString *text = [NSString lk_timeAndcontent];
            [formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"%@.jpg",text] mimeType:@"image/jpeg"];
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        BND_BLOCK_EXEC(cmUploadProgres,uploadProgress)
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [LKRespondHandler handleRespond:responseObject succeed:success failed:failure sessionManager:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self)
        [LKRespondHandler handleFailed:error failed:failure sessionManager:self];
    }];
}

@end
